import { basename, join } from "node:path"
import {
	bootstrapFs,
	packagesByScope,
	repoDirs,
	type PackageScope
} from "./shared.ts"

const { readFile, shell, rmSync, writeFile } = bootstrapFs

export const dtsGen = () => {
	const pkgScope = basename(process.cwd()) as PackageScope
	const pkg = packagesByScope[pkgScope]

	console.log(`✍️ Generating DTS bundle for ${pkg.name}...`)

	shell("pnpm tsup index.ts --dts-only --dts-resolve --format esm --out-dir .")

	const expectedDtsBundlePath = join(pkg.path, "index.d.ts")

	const rawDts = readFile(expectedDtsBundlePath)
	rmSync(expectedDtsBundlePath)

	const bundleOutputPath = join(
		repoDirs.docs,
		"components",
		"dts",
		`${pkgScope}.ts`
	)

	const rawDtsModule = `declare module "${pkg.name}" {
    ${rawDts}
}`

	const rawFileContents = `/** THIS FILE IS AUTOGENERATED FROM ark/repo/dtsGen.ts **/
// prettier-ignore
export const ${pkg.scope}Dts = ${JSON.stringify(rawDtsModule)}\n`

	// fix some tsup confusion
	const fileContents = rawFileContents.replace(
		/(Omit|Exclude|Extract|Record)\$1/g,
		"$1"
	)

	writeFile(bundleOutputPath, fileContents)

	console.log(`📚 Successfully wrote DTS bundle for ${pkg.name}!`)
}
